package com.superdry.activity;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ab.http.AbHttpUtil;
import com.ab.http.AbRequestParams;
import com.ab.http.AbStringHttpResponseListener;
import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.app.PayTask;
import com.drysurper.R;
import com.superdry.alipay.AliPayUtils;
import com.superdry.alipay.PayResult;
import com.superdry.json.Userinfo;
import com.superdry.utils.GlobalConst;
import com.superdry.utils.SPHelper;
import com.superdry.utils.StringUtils;
import com.superdry.utils.ToastHelper;

public class BalanceActivity extends Activity implements OnClickListener {

	View goback;
	RadioButton balance1000;
	RadioButton balance2000;
	RadioButton balance500;
	RadioGroup recharge_num;
	RadioGroup recharge_mode;
	TextView acount_tv;
	EditText input_balance;
	RelativeLayout ensure_recharge;
	AbHttpUtil mAbHttpUtil;
	Userinfo userInfo;
	double money = 0;// 充值的金额
	int mode = 0;// 充值方式 alipay或者weixinpay
	boolean is_chongzhi_success = false;
	private static final int ALI_PAY_FLAG = 1;
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case ALI_PAY_FLAG: {
				PayResult payResult = new PayResult((String) msg.obj);
				// 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
				String resultInfo = payResult.getResult();
				String resultStatus = payResult.getResultStatus();
				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
					is_chongzhi_success = true;
					chongzhi_success();
				} else {
					// 判断resultStatus 为非“9000”则代表可能支付失败
					// “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						Toast.makeText(BalanceActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();
					} else {
						// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
						Toast.makeText(BalanceActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
					}
				}
				break;
			}
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.aty_balance);
		initView();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	public void initView() {

		// 获取Http工具类
		mAbHttpUtil = AbHttpUtil.getInstance(this);
		mAbHttpUtil.setTimeout(10000);

		userInfo = SPHelper.getUserInfo(BalanceActivity.this);
		goback = findViewById(R.id.goback_balance);
		balance2000 = (RadioButton) findViewById(R.id.balance2000);
		balance1000 = (RadioButton) findViewById(R.id.balance1000);
		balance500 = (RadioButton) findViewById(R.id.balance500);
		input_balance = (EditText) findViewById(R.id.input_balance);
		ensure_recharge = (RelativeLayout) findViewById(R.id.ensure_recharge);
		acount_tv = (TextView) findViewById(R.id.acount_tv);
		recharge_num = (RadioGroup) findViewById(R.id.recharge_num);
		recharge_mode = (RadioGroup) findViewById(R.id.recharge_mode);

		if (null != userInfo) {
			acount_tv.setText(userInfo.getAccount() + "");
		} else {
			acount_tv.setText("0.0");
		}

		ensure_recharge.setOnClickListener(this);
		goback.setOnClickListener(this);
		input_balance.setOnClickListener(this);
		recharge_num.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup arg0, int arg1) {
				int id = arg0.getCheckedRadioButtonId();
				RadioButton checked = (RadioButton) findViewById(id);
				String money_str = checked.getText().toString();
				money = Double.parseDouble(money_str);
			}
		});
		recharge_mode.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				mode = group.getCheckedRadioButtonId();
			}
		});

	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.goback_balance:
			setDataT();
			break;

		case R.id.input_balance:
			balance2000.setChecked(false);
			balance1000.setChecked(false);
			balance500.setChecked(false);
			break;
		case R.id.ensure_recharge:
			// 支付成功后 再向服务器发出增加余额的消息
			ensureRecharge();
			break;

		default:
			break;
		}
	}

	@Override
	public void onBackPressed() {
		setDataT();
	}

	private void setDataT() {

		if (is_chongzhi_success) {
			Intent intent = new Intent();
			intent.putExtra("money", money);
			this.setResult(1, intent);
		}
		finish();
	}

	/**
	 * 充值
	 */
	private void ensureRecharge() {

		if (mode == 0) {
			ToastHelper.show(BalanceActivity.this, "请选择支付方式");
			return;
		}
		// 得到要充值的金额
		boolean verify = false;
		String money_str = input_balance.getText().toString();
		if (!StringUtils.isEmpty(money_str)) {
			try {
				money = Double.parseDouble(money_str);
			} catch (Exception e) {
				verify = true;
				ToastHelper.show(BalanceActivity.this, "输入的金额不合法");
			}
		}
		if (verify) {
			return;
		}
		// 确认支付方式
		if (mode == R.id.recharg_ali_pay) {
			// 支付宝支付
			ali_pay(money);
		} else if (mode == R.id.recharg_weixin_pay) {
			// 微信支付
		}
	}

	/**
	 * 通知服务器 支付成功
	 */
	public void chongzhi_success() {

		AbRequestParams params = new AbRequestParams();
		params.put("money", money + "");
		params.put("type", 1 + "");
		params.put("userId", userInfo.getUserID() + "");

		mAbHttpUtil.post(GlobalConst.CHONGZHI_SUCCESS, params, new AbStringHttpResponseListener() {

			@Override
			public void onStart() {
			}

			@Override
			public void onFinish() {
			}

			@Override
			public void onFailure(int statusCode, String content, Throwable error) {
				ToastHelper.show(BalanceActivity.this, "充值失败");
			}

			@Override
			public void onSuccess(int statusCode, String content) {
				ToastHelper.show(BalanceActivity.this, "充值成功");
			}
		});

	}

	/**
	 * 支付宝支付
	 */
	private void ali_pay(double money) {
		// 订单
		String orderInfo = AliPayUtils.getOrderInfo("测试的商品", "该测试商品的详细描述", money + "");
		// 对订单做RSA 签名
		String sign = AliPayUtils.sign(orderInfo);
		try {
			// 仅需对sign 做URL编码
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		// 完整的符合支付宝参数规范的订单信息
		final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + AliPayUtils.getSignType();

		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(BalanceActivity.this);
				// 调用支付接口，获取支付结果
				String result = alipay.pay(payInfo);

				Message msg = new Message();
				msg.what = ALI_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};
		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

}
